<script lang="ts" setup>
import { reactive, onMounted } from 'vue'
// import {Greet} from '../../wailsjs/go/main/App'
import { EventsOn, EventsOff } from '../../wailsjs/runtime/runtime'
import { Init, ReadPaths, WatchPath, CloseFileWatcher, LastLogs,  } from '../../wailsjs/go/core/FileWatcher'

const data = reactive<{
  paths: Array<string>,
  step: string,

  logs: Array<{ path: string, msg: string, time: string  }>
}>({
  paths: [],
  step: '',

  logs: []
})

// const fileChangeEvent = 
EventsOn("FileWatch", eventData => {
  console.log("FileWatch", eventData)
  data.logs.push(eventData)
})

const startup = async () => {
  data.step = "start"

  // await Init()

  let list : Array<string> = await ReadPaths() as Array<string>
  if (!list || list.length==0) {
    return
  }

  data.step = "load"
  let tlist : Array<Promise<any>> = []
  for(let i=0; i<list.length; i++) {
    let str = list[i]
    tlist.push(WatchPath(str))
  }

  data.step = "loading"
  data.paths = list
  console.log("paths", list)
  let re = await Promise.all(tlist)
  console.log("result", re)

  data.step = "end"
}
const dettach = async () => {
  await CloseFileWatcher()
}

const refresh = async () => {
  await dettach()
  await Init(null)

  data.logs = []
  await startup()
  await showLastLogs()
}

// 读取最后几行日志
const showLastLogs = async () => {
  data.logs = await LastLogs(20)

  console.log("data.logs", data.logs)
}

onMounted( async () => {
  //await dettach()
  await startup()
  await showLastLogs()
})

</script>

<template>
  <main>
    <div class="head-menu">
      <div class="paths">
        <div v-for="p,index in data.paths" :key="'path_'+index">
          {{ p }}
        </div>
      </div>
      <el-button type="primary" class="btnRefresh" @click="refresh">刷新</el-button>
    </div>
    <div class="logs">
      <div v-for="item, index in data.logs" :key="'log_' + index" class="log-line">
        <div>[{{ item.time }}] </div> 
        <div>【{{ item.msg }}】</div>
        <div>{{ item.path }}</div>
      </div>
    </div>
  </main>
</template>

<style scoped lang="scss">
$head-height: 40px;

.head-menu{
  position: fixed;
  height: $head-height;
  width: calc( 100% - 10px );
  margin-right: 5px;
  display: flex;
  text-align: center;
  align-items: center;
  justify-content: flex-end;

  border-bottom: 1px solid rgb(221, 86, 37);
  background-color: #f5f5f5;
}
.paths{
  flex: 1;
  color:rgb(41, 155, 155);
  &>div{
    padding-right: 10px;
    display: inline-block;
  }
}

.logs{
  padding-top: $head-height;
}

.log-line{
  display: flex;
  &:nth-child(1), &:nth-child(2) {
    flex: 1;
  }

  &>div{
    margin: 2px 3px;
  }
}
</style>
